﻿using eslib.HttpApiClient;
using NLog;

namespace ArticleClientLib
{
    /// <summary>
    /// 软文同步系统
    /// 用于同步服务器端数据到本地
    /// 可独立运行
    /// </summary>
    public class ArticleSyncSystem
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        void Info(string msg) => logger.Info(msg);
        void Error(string msg) => logger.Error(msg);

        public ArticleSyncSystem()
        {
            ArticleRoot = new ArticleRootDir(AritcleSystem.LocalRootPath);
        }



        /// <summary>
        /// 服务端软文
        /// </summary>
        public ArticleRootDir ArticleRoot { get; }


        /// <summary>
        /// 所有分类同步(不会同步分类下的软文）
        /// </summary>
        /// <returns></returns>
        public async Task ClassiflySync()
        {
            //获取分类“0”下的子分类
            await ClassiflySync(0);
        }

        /// <summary>
        /// 同步指定分类(不会同步分类下的软文）
        /// </summary>
        /// <param name="classiflyId"></param>
        /// <returns></returns>
        public async Task ClassiflySync(long classiflyId)
        {
            ArticleApi api = new();
            (bool res, string msg, List<ClassiflyJson>? idColl) res = await api.GetSubClassifly(classiflyId);
            if (!res.res)
            {
                Error(res.msg);
                return;
            }

            foreach (var c in res.idColl)
            {
                Info($"正在同步软文分类[{c.name}](ID:{c.id})");

                //确保目录存在
                ArticleRoot.EnsureClassflyExist(c);

                //继续查找子类别
                await ClassiflySync(c.id);
            }
        }

        /// <summary>
        /// 所有软文同步
        /// </summary>
        /// <returns></returns>
        public async Task ArticleSync()
        {
            foreach (Classifly c in ArticleRoot.Classiflies)
            {
                await ArticleSync(c);
            }
        }

        /// <summary>
        /// 同步一个分类下的软文
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public async Task ArticleSync(Classifly c)
        {
            //先删除本地软文
            c.RemoveAll();

            //同步本分类下的软文
            ArticleApi api = new();
            (bool res, string msg, List<long>? idColl) res = await api.GetClassiflyArticleIdCollection(c.classiflyId);
            if (!res.res)
            {
                Error(res.msg);
                return;
            }

            int total = res.idColl.Count();
            int cnt = 1;
            foreach (var id in res.idColl)
            {
                await SingleArticleSync(c, id, cnt++, total);
            }
        }

        /// <summary>
        /// 同步单个软文
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task SingleArticleSync(Classifly c, long articleId, int cnt = 0, int total = 0)
        {
            //拉取软文数据
            ArticleApi api = new();
            (bool res, string msg, ArticleSyncJson? json) = await api.SyncArticle(articleId);
            if (!res)
            {
                Error(msg);
                return;
            }

            Info($"开始同步软文({cnt}/{total}) [{json.id}]{json.title}");

            //保存到本地
            SyncArticle sart = new(c, json);
            await sart.Save();

            if (total != 0)
                Info($"同步完成 {cnt}/{total}");
            else
                Info($"同步完成");
        }


        public async Task<bool> Remove(LocalArticle a)
        {
            ArticleApi api = new();
            (bool res, string msg, ObjectJsonResult? data) res = await api.RemoveGenericArticle(a);
            if (!res.res)
            {
                Error(res.msg);
                return false;
            }

            return res.data.success;
        }
    }



    public delegate void LogCallback(string message);
}
